# leetcode 94 二叉树的中序遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        left = self.inorderTraversal(root.left)
        right = self.inorderTraversal(root.right)
        return left + [root.val] + right


# 非递归实现
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        # 根节点入栈，根节点的左节点入栈，直到遇到左节点为空，则开始出栈
        # 出栈判断右节点，右节点不为空则入栈
        # 右节点为空继续出栈

        if not root:
            return []
        result = []
        stack = []
        curr = root
        while stack or curr:
            if curr is not None:
                stack.append(curr)
                curr = curr.left
            else:
                curr = stack.pop()
                result.append(curr.val)
                curr = curr.right
        return result
